﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class UIController : MonoBehaviour
{
    public List<AppUI> panels;
    
    AppUI m_CurShowPanel;
    AppUI m_PrePanel;
    public AppUI prePanel => m_PrePanel;

    public MainPanel defaultPanel;

    static UIController _instance;
    public static UIController instance => _instance;
    void Awake()
    {
        _instance = this;
    }

    void Start()
    {
        foreach(var panel in panels)
        {
            panel.gameObject.SetActive(false);
        }

        ShowUI<MainPanel>();
    }

    public AppUI GetUI<T>() where T : AppUI
    {
        return panels.Find(e => e.GetType() == typeof(T));
    }
    public AppUI ShowUI(Type appUIType) 
    {
        m_PrePanel = m_CurShowPanel;

        if (m_CurShowPanel)
        {
            if (m_CurShowPanel.GetType() == appUIType)
            {
                return m_CurShowPanel;
            }

            var prePanel = m_CurShowPanel;
            prePanel.DoOnDisactive();
            prePanel.PlayHideAnim(() =>
            {
                //GameDebug.Log($"{prePanel.name}  隐藏");
                prePanel.gameObject.SetActive(false);
            });
        }
        GameDebug.Log($"{m_CurShowPanel?.GetType()} 转到 {appUIType}");

        AppUI panel = panels.Find(e => e.GetType() == appUIType);
        if (panel)
        {
            if (m_CurShowPanel)
            {
                m_CurShowPanel.nextUI = panel.GetType();

                if (panel.nextUI != m_CurShowPanel.GetType())
                    panel.preUI = m_CurShowPanel.GetType();
            }
            m_CurShowPanel = panel;

            panel.gameObject.SetActive(true);
            panel.DoOnActive();
            panel.PlayShowAnim(null);

            //GameDebug.Log($"显示 {panel.name}");
        }
        return panel;
    }

    public T ShowUI<T>() where T: AppUI
    {
        AppUI panel = ShowUI(typeof(T));

        //m_PrePanel = m_CurShowPanel;

        //if (m_CurShowPanel)
        //{
        //    m_CurShowPanel.DoOnDisactive();
        //    m_CurShowPanel.PlayHideAnim(() =>
        //    {
        //        m_CurShowPanel.gameObject.SetActive(false);
        //    });
        //}

        //AppUI panel = panels.Find(e => e.GetType() == typeof(T));
        //if (panel)
        //{
        //    m_CurShowPanel = panel;

        //    m_CurShowPanel.gameObject.SetActive(true);
        //    m_CurShowPanel.DoOnActive();
        //    panel.PlayShowAnim(null);
        //}

        return panel as T;
    }
}
